package rainy.file.synchronization;

import java.net.InetAddress;

import rainy.file.synchronization.client.FileSendClient;
import rainy.file.synchronization.config.RainyRunTime;
import rainy.file.synchronization.server.MonitorServer;

/**
 * README
 * 
 * This is the tool for several server to sync their folder into one server
 * 
 * 
 * Start the server
 * 
 * @author dongwenbin
 * 
 */
public class App {
	private static final String configfile = "rainy.conf";
	private static final String serverTypeKey = "rainy.type";
	private static final String master = "master";
	private static final String slave = "slave";

	public static void main(String[] args) throws Exception {
		String config = System.getProperty(configfile);
		if (config == null || config.trim().equals("")) {
			config = "rainy.properties";
		}

		String serverType = System.getProperty(serverTypeKey);
		if (serverType == null || serverType.trim().equals("")) {
			serverType = slave;
		}

		String serverName = getLocalHostName();
		String configuredServerName = RainyRunTime.getPropDefine("rainy.master.serverName");
		if (serverName.trim().equalsIgnoreCase(configuredServerName.trim())) {
			serverType = master;
			System.out.println("[APP LUNCHER] this server is determined to be the master! serverName: " + serverName);
		}
		String[] ips = getAllLocalHostIP();
		for (String ip : ips) {
			if (ip.trim().equalsIgnoreCase(configuredServerName.trim())) {
				System.out.println("[APP LUNCHER] this server is determined to be the master! ip: " + ip);
			}
		}
		System.out.println("[APP LUNCHER] this server is determined to be the slave!");
		if (serverType.equals(master)) {
			new MonitorServer().run();
		} else {
			new FileSendClient().run();
		}
	}

	public static String getLocalHostName() {
		String hostName;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostName = addr.getHostName();
		} catch (Exception ex) {
			hostName = "";
		}
		return hostName;
	}

	public static String[] getAllLocalHostIP() {
		String[] ret = null;
		try {
			String hostName = getLocalHostName();
			if (hostName.length() > 0) {
				InetAddress[] addrs = InetAddress.getAllByName(hostName);
				if (addrs.length > 0) {
					ret = new String[addrs.length];
					for (int i = 0; i < addrs.length; i++) {
						ret[i] = addrs[i].getHostAddress();
					}
				}
			}

		} catch (Exception ex) {
			ret = null;
		}
		return ret;
	}
}
